package org.iabako.server.servlet;

import org.apache.poi.util.IOUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by jose on 15/09/14.
 */
public class DownloadFileServlet extends HttpServlet {

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String fileToken = req.getParameter("fileToken");
        String fileAbsolutePath = (String) req.getSession().getAttribute(fileToken);

        if (fileAbsolutePath == null) {
            //Avoid double click problems, specially in mobile devices
            return;
        }

        String fileName = (String) req.getSession().getAttribute(fileToken + "_fileTitle");

        resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        OutputStream out = resp.getOutputStream();

        FileInputStream in = new FileInputStream(fileAbsolutePath);
        IOUtils.copy(in, out);
        in.close();
        out.close();

        req.getSession().removeAttribute(fileToken);
        req.getSession().removeAttribute(fileToken + "_fileTitle");

        File tmpFile = new File(fileAbsolutePath);
        tmpFile.delete();
    }
}
